#!/usr/bin/env python3
"""
@Project    ：learn-algorithm
@File       ：io_handle.py
@Author     ：qqq
@Time       ：2024/4/14 12:17
@Annotation : “”
@Intro      : 输入输出重定向
"""
import os
import sys


class SysIORedirect:
    @staticmethod
    def check_filepath(filepath: str):
        """
        Intro:
            检查文件是否存在，不存在则创建
        Args:
            filepath:
        Returns:
        """
        if not filepath:
            raise ValueError("filepath is empty")

        if not os.path.exists(path=filepath):
            with open(filepath, "w") as fw:
                fw.write("")
            print(f"file {filepath} not exists but create now")
            exit(0)

    @staticmethod
    def i(filepath: str):
        """
        Intro:
              重定向输入
        Args:
            filepath:
        Returns:
        """
        SysIORedirect.check_filepath(filepath)
        sys.stdin = open(file=filepath, mode="r")

    @staticmethod
    def o(filepath):
        """
        Intro:
            重定向输出
        Args:
            filepath:
        Returns:
        """
        SysIORedirect.check_filepath(filepath=filepath)
        sys.stdout = open(file=filepath, mode="w")
